package dao;

import beans.HttpConfig;
import beans.Log;
import beans.UserLog;
import db.DBDruidManager;
import utils.Log4jInit;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


public class LogDao {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //timeLimit：用于控制日志显示的时间长短，只显示前TIME_LIMIT天的日志
    private static String TIME_LIMIT = HttpConfig.timeLimit;
    /**
     * 用于查询Log具体信息
     * @param userId
     * @param page
     * @author 杨凯文
     * 每页10条记录
     *
     */
    public List<Log> getLogInfoByUserId(int userId,int page){
        try {
            List<Log> logList=new ArrayList<>();
            String sql="select * from log where user_id= ? limit ?,10";
            PreparedStatement statement= DBDruidManager.getConnection().prepareStatement(sql);
            statement.setInt(1,userId);
            statement.setInt(2,(page-1)*10);
            ResultSet set=statement.executeQuery();
            while (set.next()){
                logList.add(new Log(set.getInt("user_id"),
                        new Date(set.getDate("time").getTime()),
                        set.getString("operate"),
                        set.getString("result")));
            }
            return logList;

        } catch (SQLException e) {
            e.printStackTrace();
        }


        return null;
    }

    public List<Object> userLogDetail(String sql, Object[] params){
        final List<Object> results = new ArrayList<>();
        return Query.executeQueryList(results, sql,params, new QueryCallBackList() {
            @Override
            public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
                try {
                    while (rs.next()) {
                        UserLog userLog = new UserLog();
                        userLog.setLogId(rs.getString("log_id"));
                        userLog.setUserId(rs.getString("user_id"));
                        userLog.setUserName(rs.getString("user_name"));
                        userLog.setTime(simpleDateFormat.format(simpleDateFormat.parse(rs.getString("time"))));
                        userLog.setLogLevel(rs.getString("log_level"));
                        userLog.setOperateTarget(rs.getString("operate_target"));
                        userLog.setOperateType(rs.getString("operate_type"));
                        userLog.setResult(rs.getString("result").trim());
                        results.add(userLog);
                    }
                } catch (SQLException | ParseException e) {
                    e.printStackTrace();
                }
                return results;
            }
        });
    }

    public List<Object> logList(Integer onePageCount, Integer currentPage) {
        String sql = "select * from user_log log,`user` where TO_DAYS(now()) - TO_DAYS(time) <= "+ TIME_LIMIT +" and " +
                " log.user_id = `user`.user_id order by time desc limit "
                + (currentPage - 1) * onePageCount + " , " + onePageCount;
        return userLogDetail(sql,null);
    }

    public int getLogPageNum(Integer onePageCount) {
        int modelNum = this.userLogNum();
        return (modelNum % onePageCount) == 0 ? (modelNum / onePageCount) : (modelNum / onePageCount + 1);
    }

    /**
     * 平台用户操作日志的全文搜索
     * @param onePageCount
     * @param currentPage
     * @param match
     * @param startTime
     * @param endTime
     * @return
     */
    public List<Object> logFulltextSearch(Integer onePageCount, Integer currentPage, String match, String startTime, String endTime){
        String startTimeString = startTime==null?"":" and time >= ? ";
        String endTimeString = endTime==null?"":" and time <= ? ";
        String matchString = match==null?"":" and (log_level REGEXP ?  or operate_target REGEXP ? or operate_type REGEXP ? or result REGEXP ?) " ;
        Object[] params = null;
        String sql = "select * from user_log,`user` where TO_DAYS(now()) - TO_DAYS(time) <= "+ TIME_LIMIT +" and `user`.user_id=user_log.user_id " + matchString
                + startTimeString + endTimeString + "order by time desc limit "
                + (currentPage - 1) * onePageCount + " , " + onePageCount;
        List<Object> paramsList = new ArrayList<>();
        if(match!=null)
            paramsList.addAll(Arrays.asList(match, match, match, match));
        if(startTime!=null)
            paramsList.add(startTime);
        if(endTime!=null)
            paramsList.add(endTime);
        if(paramsList.size()>0)
        {
            params = new Object[paramsList.size()];
            for(int i=0;i<paramsList.size();i++)
            {
                params[i] = paramsList.get(i);
            }
        }
        return userLogDetail(sql,params);
    }



    /**
     * 平台操作日志搜索结果页数计算
     * @param onePageCount
     * @param currentPage
     * @param match
     * @param startTime
     * @param endTime
     * @return
     */
    public int logFulltextSearchNum(Integer onePageCount, Integer currentPage, String match, String startTime, String endTime){
        String startTimeString = startTime==null?"":" and time >= ? ";
        String endTimeString = endTime==null?"":" and time <= ? ";
        String matchString = match==null?"":" and (log_level REGEXP ?  or operate_target REGEXP ? or operate_type REGEXP ? or result REGEXP ?) " ;
        Object[] params = null;
        String sql = "select count(*) from user_log,`user` where TO_DAYS(now()) - TO_DAYS(time) <= "+ TIME_LIMIT
                +" and  `user`.user_id=user_log.user_id " + matchString
                + startTimeString + endTimeString;
        List<Object> paramsList = new ArrayList<>();
        if(match!=null)
            paramsList.addAll(Arrays.asList(match, match, match, match));
        if(startTime!=null)
            paramsList.add(startTime);
        if(endTime!=null)
            paramsList.add(endTime);
        if(paramsList.size()>0)
        {
            params = new Object[paramsList.size()];
            for(int i=0;i<paramsList.size();i++)
            {
                params[i] = paramsList.get(i);
            }
        }
        int modelNum = PublicDao.oneNum(sql,params);
        return (modelNum % onePageCount) == 0 ? (modelNum / onePageCount) : (modelNum / onePageCount + 1);
    }

    public int userLogNum() {
        String sql = "select count(*) from user_log where TO_DAYS(now()) - TO_DAYS(time) <= "+ TIME_LIMIT ;
        return PublicDao.oneNum(sql,null);
    }

    public static void main(String[] args) {
        try {
        	Log4jInit.logger.info(simpleDateFormat.format(simpleDateFormat.parse("2017-9-12 17:19:00.0")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

